﻿using DataMgr.mode;
using DataMgr.msg;
using DataMgr.ui_control;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.ListView;

namespace DataMgr
{
    public partial class DataMgr : Form
    {
        delegate void AsynUpdateUI(int step);
        DataTable m_downDataTable = new DataTable();
        List<HisTestInfo> m_listData;
        private bool bUserLogin = false;
        //MyDb m_myDb = new MyDb();
        DownManager m_downMgr = new DownManager();
        private SocketServer m_tcpServer = new SocketServer();
        List<string> g_StrLogEvent = new List<string>{ "无效","完成","启动","暂停","接续","停止","跳转","断电","上电","中位机磁盘满","工步转换","工步保护","工步结束","工步跳转", "","","","","DC通讯故障","","DC故障", "","",""};
        public DataMgr()
        {
            InitializeComponent();
            IniList();
            m_tcpServer.Start();
            Console.WriteLine("进程主线程：{0} ", Thread.CurrentThread.ManagedThreadId.ToString());

            m_downMgr.BeginThread();

            downListView.ListViewItemSorter = new ListViewColumnSorter();
            downListView.ColumnClick += new ColumnClickEventHandler(ListViewHelper.listView_columnClick);

            ResetCtrl();
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键  
            {
                if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字  
                {
                    e.Handled = true;
                }
            }
        }

        private void buttonDel_Click(object sender, EventArgs e)
        {
            this.buttonDel.Enabled = false;
            this.buttonQuery.Enabled = false;
            this.buttonDel.Text = "正在删除";
            DeleteThread qThread = new DeleteThread();
            qThread.SelectedItems = this.listHisTest.SelectedItems;
            qThread.Form = this;
            qThread.UpdateUIDelegate = UpdataUIStatus;
            foreach (ListViewItem item in this.listHisTest.SelectedItems)
            {
                if (item.ImageIndex < m_listData.Count)
                    qThread.ListData.Add(m_listData[item.ImageIndex]);
            }
            Thread childThread = new Thread(qThread.ThreadRun);
            childThread.Start(qThread);
            //foreach (ListViewItem item in this.listHisTest.SelectedItems)
            //{
            //    if (item.ImageIndex < m_listData.Count)
            //        myDb.DeleteTestData(m_listData[item.ImageIndex]);
            //}

            //this.buttonQuery.PerformClick();
        }

        private void checkAll_CheckedChanged(object sender, EventArgs e)
        {
           

            this.listHisTest.BeginUpdate();
            for (int i = 0; i < this.listHisTest.Items.Count; ++i)
            {
                this.listHisTest.Items[i].Selected = this.checkAll.Checked;
            }
            this.listHisTest.EndUpdate();
        }
        public static void CallToChildThreadQuery(object hashtable)
        {
            Console.WriteLine("Child thread starts");
            
        }
        private void buttonQuery_Click(object sender, EventArgs e)
        {
            Hashtable hashtable = new Hashtable();
            if (this.radioDevChl.Checked)
            {
                hashtable.Add("DevId", this.textDev.Text);
                hashtable.Add("ChlId", this.textChl.Text);
            }
            else if (this.radioBarcode.Checked)
            {
                hashtable.Add("Barcode", this.textBarcode.Text);
            }

            if (this.radioBeyond.Checked)
            {
                hashtable.Add("Days", this.textDays.Text);
            }
            else if (this.radioFrom.Checked)
            {
                hashtable.Add("FromDate", this.dateFrom.Value.ToFileTimeUtc().ToString());
                hashtable.Add("ToDate", this.dateTo.Value.ToFileTimeUtc().ToString());
            }

            this.buttonDel.Enabled = false;
            this.buttonQuery.Enabled = false;
            this.buttonQuery.Text = "正在查询";
            //ThreadStart childref = new ThreadStart(CallToChildThreadQuery);
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString() + "：new thrad");
            QueryThread qThread = new QueryThread();
            qThread.Htm = hashtable;
            qThread.Form = this;
            qThread.UpdateUIDelegate = UpdataUIStatus;
            Thread childThread = new Thread(qThread.ThreadRun);
            childThread.Start(qThread);
            Console.WriteLine("In Main: Creating the Child thread");
            //Thread childThread = new Thread(CallToChildThreadQuery);
            //childThread.Start(hashtable);
            
        }
        //更新UI
        private void UpdataUIStatus(int step)
        {
            if (InvokeRequired)
            {
                this.Invoke(new AsynUpdateUI(delegate (int s)
                {
                    if (1 == step)
                    {
                        Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString() + "：update msg thread");
                        this.UpdataList();
                    }
                    else
                    {
                        this.buttonQuery.Enabled = true;
                        this.buttonQuery.Text = "查询";
                        this.buttonQuery.PerformClick();
                    }
                    //this.pgbWrite.Value += s;
                    //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
                }), step);
            }
            else
            {
                this.buttonQuery.Enabled = true;
                this.buttonQuery.Text = "查询";
                this.buttonDel.Enabled = true;
                this.buttonDel.Text = "永久删除";
                //this.pgbWrite.Value += step;
                //this.lblWriteStatus.Text = this.pgbWrite.Value.ToString() + "/" + this.pgbWrite.Maximum.ToString();
            }
        }
        public static System.DateTime ConvertIntDateTime(double d)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddMilliseconds(d);
            return time;
        }

        public void SetList(List<HisTestInfo> m)
        {
            m_listData = m;
        }

        //更新历史数据查询列表
        public void UpdataList()
        {
            this.listHisTest.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度
            this.listHisTest.Items.Clear();
            for (int i = 0; i < m_listData.Count; i++)   //添加10行数据
            {
                ListViewItem lvi = new ListViewItem();

                lvi.ImageIndex = i;     //通过与imageList绑定，显示imageList中第i项图标

                lvi.Text = m_listData[i].DevId.ToString() + "-" + m_listData[i].ChlId.ToString();

                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
                DateTime dt = startTime.AddMilliseconds(m_listData[i].StartTime);
                lvi.SubItems.Add(dt.ToString());

                lvi.SubItems.Add(m_listData[i].RecordCount.ToString());
                lvi.SubItems.Add(m_listData[i].Barcode);
                if (m_listData[i].LastLog < g_StrLogEvent.Count)
                {
                    lvi.SubItems.Add(g_StrLogEvent[m_listData[i].LastLog]);
                }


                this.listHisTest.Items.Add(lvi);
            }

            this.listHisTest.EndUpdate();  //结束数据处理，UI界面一次性绘制。
            ListViewChange listChange = new ListViewChange();
            listChange.AutoResizeColumnWidth(this.listHisTest);
            this.buttonQuery.Enabled = true;
            this.buttonQuery.Text = "查询";
            this.buttonDel.Enabled = true;
            this.buttonDel.Text = "永久删除";
            //notifyIcon1.ContextMenuStrip = contextMenuStrip1;
        }

        private void DataMgr_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("退出将不自动下载数据，是否退出?", "警告", 
                MessageBoxButtons.OKCancel, MessageBoxIcon.Warning))
            {
                System.Environment.Exit(0);
                return;
            }
            //MessageBox.Show("程序将最小化到系统托盘区");
            e.Cancel = true;
            HideMainFrm();
        }
        private void HideMainFrm()
        {
            // 取消关闭窗体 
            this.Hide();
            this.ShowInTaskbar = false;//取消窗体在任务栏的显示
            this.notifyIcon1.Visible = true;//显示托盘图标
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            
            this.Show(); // 窗体显现
            this.WindowState = FormWindowState.Normal; //窗体回复正常大小
            this.ShowInTaskbar= true;
            this.notifyIcon1.Visible = false;
        }

        private void DataMgr_Deactivate(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
                HideMainFrm();
        }

        private void downStateTimer_Tick(object sender, EventArgs e)
        {
            if (this.downListView.Visible)
            {
                //this.downListView.Items.Clear();
                foreach (ChannelTestInfo item in DownManager.m_testInfo)
                {
                    string devChl = item.Request.devId + "-" + item.Request.chlId;
                    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
                    DateTime dt = startTime.AddMilliseconds(item.StartTime);
                    string testTime = dt.ToString();

                    bool bExist = false;
                    foreach (ListViewItem itemRow in downListView.Items)
                    {
                        if (itemRow.SubItems[0].Text == devChl && itemRow.Tag as string == item.Request.guidPath)
                        {
                            bExist = true;
                            string s2 = "" + item.LastSeq;
                            string s3 = item.LastUpdateTime.ToString();
                            string s4 = ChannelTestInfo.GetState(item.State);

                            {
                                itemRow.SubItems[1].Text = testTime;
                                itemRow.SubItems[2].Text = s2;
                                itemRow.SubItems[3].Text = s3;
                                itemRow.SubItems[4].Text = s4;
                                string sLog = "更新数据：";
                                for (int i = 0; i < 5; i++)
                                {
                                    sLog += itemRow.SubItems[i].Text + ",";
                                }

                                MsgUtil.WriteLog(sLog);
                            }
                        }
                    }

                    if (!bExist)
                    {
                        ListViewItem li = new ListViewItem(devChl);
                        li.SubItems.Add(testTime);
                        li.SubItems.Add("" + item.LastSeq);
                        li.SubItems.Add(item.LastUpdateTime.ToString());
                        li.SubItems.Add(ChannelTestInfo.GetState(item.State));
                        li.Tag = item.Request.guidPath;
                        downListView.Items.Insert(0, li);
                        //;// + devChl+" " + li.SubItems[)
                        string sLog = "添加数据：";
                        for (int i = 0; i < 5; i++)
                        {
                            sLog += li.SubItems[i].Text + ",";
                        }

                        MsgUtil.WriteLog(sLog);
                    }
          
                }

                //m_downDataTable.Clear();
                //m_downDataTable.Columns.Add("通道");
                //m_downDataTable.Columns.Add("启动时间");
                //m_downDataTable.Columns.Add("当前记录数");
                //m_downDataTable.Columns.Add("最后下载时间");
                //m_downDataTable.Columns.Add("当前状态");
            }
        }

        private void Login_Click(object sender, EventArgs e)
        {
            LoginForm log = new LoginForm();
            if (DialogResult.OK == log.ShowDialog())
            {
                this.buttonDel.Enabled = true;
                this.lUser.Text = log.User;
                bUserLogin = true;
                this.btnLogin.Enabled = false;
                this.buttonDel.Enabled = true;
                this.btnLogout.Enabled = true;
            }
        }

        private void logout_Click(object sender, EventArgs e)
        {
            ResetCtrl();
        }

        private void ResetCtrl()
        {
            this.buttonDel.Enabled = false;
            this.lUser.Text = "未登录";
            bUserLogin = false;
            this.btnLogin.Enabled = true;
            this.buttonDel.Enabled = false;
            this.btnLogout.Enabled = false;
        }
        //int m_sortStarttime = -1;
        //private void downListView_ColumnClick(object sender, ColumnClickEventArgs e)
        //{

        //}
    }
    public class QueryThread
    {
        public Hashtable Htm { set; get; }
        public DataMgr Form { set; get; }
        public delegate void UpdateUI(int step);//声明一个更新主线程的委托
        public UpdateUI UpdateUIDelegate;
        public void ThreadRun(object o)
        {
            QueryThread qt = o as QueryThread;
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString() + "：run thrad");
            MyDb myDb = new MyDb();
            Form.SetList(myDb.QueryHisTest(qt.Htm));
            qt.UpdateUIDelegate(1);
        }
    }

    public class DeleteThread
    {
        public SelectedListViewItemCollection SelectedItems { set; get; }
        public List<HisTestInfo> ListData = new List<HisTestInfo>();
        public DataMgr Form { set; get; }
        public delegate void UpdateUI(int step);//声明一个更新主线程的委托
        public UpdateUI UpdateUIDelegate;
        public void ThreadRun(object o)
        {
            DeleteThread qt = o as DeleteThread;
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString() + "：run thrad del");
            MyDb myDb = new MyDb();
            myDb.Init();
            foreach (HisTestInfo item in ListData)
            {
                myDb.DeleteTestData(item);
            }

            //Form.SetList(myDb.QueryHisTest(qt.Htm));
            qt.UpdateUIDelegate(0);
        }
    }

    class ListViewChange
    {
        //自动调整ListView的列宽的方法
        public void AutoResizeColumnWidth(ListView lv)
        {
            int count = lv.Columns.Count;
            int MaxWidth = 0;
            Graphics graphics = lv.CreateGraphics();
            int width;
            lv.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            for (int i = 0; i < count; i++)
            {
                string str = lv.Columns[i].Text;
                MaxWidth = lv.Columns[i].Width;

                foreach (ListViewItem item in lv.Items)
                {
                    str = item.SubItems[i].Text;
                    width = (int)graphics.MeasureString(str, lv.Font).Width;
                    if (width > MaxWidth)
                    {
                        MaxWidth = width;
                    }
                }
                if (MaxWidth <= 150)
                {
                    lv.Columns[i].Width = MaxWidth;
                }
                else
                {
                    lv.Columns[i].Width = 150;
                }
            }
        }
    }

   
}
